﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workflow.Application.DTOs.Input;
using Workflow.Application.DTOs.Output;
using Workflow.Application.ErrorCode;
using Workflow.Application.Extend;
using Workflow.Application.IService;
using Workflow.Domain.Models;
using Workflow.Infrastructure.IRepository;
using WorkflowCore.Interface;
using Yitter.IdGenerator;

namespace Workflow.Application.Service
{
    public class GroupService : IGroupService
    {
        private readonly IBaseRepository<AuditModel> auditBase;
        private readonly IBaseRepository<WorkflowDefinitionModel> definitionBase;
        private readonly IBaseRepository<WorkflowInstanceModel> instanceBase;
        private readonly IBaseRepository<WorkflowGroupModel> groupBase;
        /// <summary>
        /// automapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// token上下文
        /// </summary>
        private readonly IHttpContextAccessor contextAccessor;
        private readonly IWorkflowHost workflowHost;
        /// <summary>
        /// 流程注册
        /// </summary>
        private readonly IWorkflowRegistry workflowRegistry;
        private readonly IDefinitionLoader definitionLoader;
        private readonly ILogger<WorkflowService> logger;
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="auditBase"></param>
        /// <param name="definitionBase"></param>
        /// <param name="instanceBase"></param>
        /// <param name="groupBase"></param>
        /// <param name="mapper"></param>
        /// <param name="contextAccessor"></param>
        /// <param name="workflowHost"></param>
        /// <param name="workflowRegistry"></param>
        /// <param name="definitionLoader"></param>
        /// <param name="logger"></param>
        public GroupService(
            IBaseRepository<AuditModel> auditBase,
            IBaseRepository<WorkflowDefinitionModel> definitionBase,
            IBaseRepository<WorkflowInstanceModel> instanceBase,
            IBaseRepository<WorkflowGroupModel> groupBase,
            IMapper mapper,
            IHttpContextAccessor contextAccessor,
            IWorkflowHost workflowHost,
            IWorkflowRegistry workflowRegistry,
            IDefinitionLoader definitionLoader,
            ILogger<WorkflowService> logger)
        {
            this.auditBase = auditBase;
            this.definitionBase = definitionBase;
            this.instanceBase = instanceBase;
            this.groupBase = groupBase;
            this.mapper = mapper;
            this.contextAccessor = contextAccessor;
            this.workflowHost = workflowHost;
            this.workflowRegistry = workflowRegistry;
            this.definitionLoader = definitionLoader;
            this.logger = logger;
        }
        /// <summary>
        /// 获取流程模板分组列表
        /// </summary>
        /// <returns>流程模板分组列表</returns>
        public async Task<ApiResult<List<WorkflowGroupDto>>> GetGroupsAsync()
        {
            try
            {
                ApiResult<List<WorkflowGroupDto>> res =new ApiResult<List<WorkflowGroupDto>>();
                // 获取所有未删除的流程模板分组，并按创建时间降序排序
                var groups = await groupBase.GetAll().Where(x => x.IsDeleted == false).ToListAsync();

                // 返回结果
                
                res.Code = StateCodeEnum.Ok;
                res.Message = "获取成功";
                res.Data = mapper.Map<List<WorkflowGroupDto>>(groups);
                return res;
               
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取流程模板分组列表失败");
                return new ApiResult<List<WorkflowGroupDto>>
                {
                    Code = StateCodeEnum.Fail,
                    Message = "获取流程模板分组列表失败: " + ex.Message,
                    Data = new List<WorkflowGroupDto>()
                };
            }
        }
        /// <summary>
        /// 添加流程模板分组
        /// </summary>
        /// <param name="input">分组信息</param>
        /// <returns>添加结果</returns>
        public async Task<ApiResult<long>> AddGroupAsync(AddGroupInput input)
        {
            try
            {
                // 检查分组名称是否已存在
                var existingGroup = await groupBase.GetAll()
                    .FirstOrDefaultAsync(x => x.GroupName == input.GroupName && !x.IsDeleted);
                
                if (existingGroup != null)
                {
                    return new ApiResult<long>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "分组名称已存在",
                        Data = 0
                    };
                }

                // 获取当前用户ID
                var currentUserId = GetCurrentUserId();
                if (currentUserId <= 0)
                {
                    return new ApiResult<long>
                    {
                        Code = StateCodeEnum.Fail,
                        Message = "获取当前用户信息失败",
                        Data = 0
                    };
                }

                // 创建新的分组
                var newGroup = new WorkflowGroupModel
                {
                    Id = YitIdHelper.NextId(), // 使用雪花算法生成ID
                    GroupName = input.GroupName,
                    CreatedUserId = currentUserId,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now,
                    IsDeleted = false
                };

                // 添加到数据库
                await groupBase.AddRange(newGroup);

                return new ApiResult<long>
                {
                    Code = StateCodeEnum.Ok,
                    Message = "添加成功",
                    Data = newGroup.Id
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "添加流程模板分组失败");
                return new ApiResult<long>
                {
                    Code = StateCodeEnum.Fail,
                    Message = "添加流程模板分组失败: " + ex.Message,
                    Data = 0
                };
            }
        }

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        /// <returns>当前用户ID</returns>
        private long GetCurrentUserId()
        {
            try
            {
                // 从HttpContext中获取当前用户ID
                var userIdClaim = contextAccessor.HttpContext?.User?.Claims?.FirstOrDefault(c => c.Type == "UserId");
                if (userIdClaim != null && long.TryParse(userIdClaim.Value, out long userId))
                {
                    return userId;
                }
                return 0;
            }
            catch
            {
                return 0;
            }
        }
    }
}
